package com.ruoyi.workFlow.service.impl;

import cn.hutool.core.util.StrUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.workFlow.service.OperationalWorkFlowService;
import com.ruoyi.worker.domain.AttendanceGroup;
import com.ruoyi.worker.domain.AttendanceInfo;
import com.ruoyi.worker.domain.OperationalRequirementsTable;
import com.ruoyi.worker.mapper.AttendanceGroupMapper;
import com.ruoyi.worker.mapper.AuditRecordMapper;
import com.ruoyi.worker.mapper.OperationalManagementMapper;
import com.ruoyi.worker.mapper.SchemeConfigurationMapper;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.engine.impl.identity.Authentication;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName OperationalWorkFlowServiceImpl
 * @Description 运营需求单审核执行流程服务层(通用工作流)
 * @Author leizhang
 * Date 2021/10/26 4:03 下午
 * @Version 1.0
 **/
@Service
public class OperationalWorkFlowServiceImpl implements OperationalWorkFlowService {

    @Autowired
    private AuditRecordMapper auditRecordMapper;
    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private SchemeConfigurationMapper schemeConfigurationMapper;

    @Autowired
    private OperationalManagementMapper operationalManagementMapper;
    @Autowired
    private AttendanceGroupMapper attendanceGroupMapper;

    /**
     * @param requestMap {"processType":"流程业务类型 1-运营单需求","processInstanceName":"运行实例的名称","businessKey":"业务关联id","processDefinitionKey":"业务实例id","variables":{"auditFlag":"参数:是否超限 1-超限 0-未超限","orderCode":"订单编号"}} variables为Map对象
     * @return void
     * @Description : 启动运营需求单实例（流程实例启动公用方法，processDefinitionKey对应实例的名称）
     * @Author : leizhang
     * @Date 4:04 下午 2021/10/26
     **/
    @Override
    public String startOperationalWorkFlowProcess(Map<String, Object> requestMap) {
        if (null == requestMap || requestMap.isEmpty()) {
            throw new IllegalArgumentException("请求参数异常");
        }
        //****2021-11-6 设置任务发起人
        Authentication.setAuthenticatedUserId(SecurityUtils.getUserId().toString());
        //必传参数 businessKey 校验
        String processDefinitionKey = null;
        if (null == requestMap.get("processDefinitionKey") || StrUtil.isEmpty(processDefinitionKey = requestMap.get("processDefinitionKey").toString())) {
            throw new IllegalArgumentException("processDefinitionKey 参数异常");
        }
        Map<String, Object> variables = null == requestMap.get("variables") ? Maps.newHashMap() : (Map<String, Object>) requestMap.get("variables");
        //****2021-11-07 添加操作者
        variables.put("createName", SecurityUtils.getUsername());
        variables.put("processType", requestMap.get("processType"));
        variables.put("startTime", new Date());
        String businessKey ="yyxq_";
        if(Integer.parseInt(requestMap.get("processType").toString())==2){
            businessKey ="lsgkq_";
        }
        //1.activiti 流程实例启动
        ProcessInstance process = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withName(requestMap.get("processInstanceName").toString())
                .withBusinessKey(null == requestMap.get("businessKey") ? "" : businessKey.concat(requestMap.get("businessKey").toString()))
                .withVariables(variables)
                .withProcessDefinitionKey(processDefinitionKey)
                .build()
        );


        if (null == requestMap.get("businessKey")) {
            return process.getId();
        }
        //更新状态
        switch (Integer.parseInt(requestMap.get("processType").toString())) {
            case 1:
//                requestMap.put("id",requestMap.get("businessKey"));
//                requestMap.put("auditResult",1);
//                requestMap.put("auditTime",new Date());
//                operationalManagementMapper.updateAuditStatus(requestMap);
                break;

            case 2:
                //临时工考勤
                long id = Long.parseLong(requestMap.get("businessKey") + "");
                this.attendanceGroup(id);
                break;
            default:
                break;
        }
        return process.getId();
    }

    /**
     * @description: 处理临时工考勤汇总表和明细表
     * @author 刘松山
     * @date 2021/12/24 15:36
     */
    public void attendanceGroup(long id) {
        AttendanceInfo a = new AttendanceInfo();
        a.setId(id);

        AttendanceInfo attendanceInfo = attendanceGroupMapper.getAttendanceStatistics(a);
        AttendanceGroup attendanceGroup = new AttendanceGroup();
        attendanceGroup.setWorkTime(attendanceInfo.getWorkTime());
        //0 待确认 1 待处理  2 已经驳回 3  已确认 4 待审核
        attendanceGroup.setCheckFlag(4);
        attendanceGroupMapper.modifyAttendanceSum(attendanceGroup);
        a.setStatus(4);
        attendanceGroupMapper.modifyAttendanceInfo(a);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOperationalRequirementsTable(Map<String,Object> operationalRequirementsTable) {
        Integer taskNode = Integer.parseInt(operationalRequirementsTable.get("taskNode").toString());
        Integer status = 0;
        if (taskNode == 2) {
            if (null != operationalRequirementsTable.get("urls")) {
                List<String> uploadFiles = (List<String>) operationalRequirementsTable.get("urls");
                if (!uploadFiles.isEmpty()) {
                    String urls = Joiner.on(";").join(uploadFiles);
                    operationalRequirementsTable.put("uploadFiles",urls);
                }
            }
            //先删除
            List<Integer> ids = Lists.newArrayList();
            ids.add(Integer.parseInt(operationalRequirementsTable.get("id").toString()));
            operationalManagementMapper.delOperationalDetailInfos(ids);
            // 质量审核通过，填写用工评估
            schemeConfigurationMapper.addOperationalRequirementsDetails((List)operationalRequirementsTable.get("deps"), Integer.parseInt(operationalRequirementsTable.get("id").toString()));
        }
        //获取当前节点
        if (taskNode == 5) {
            status = 11;
        } else if (taskNode == 2) {
            status = 4;
        } else if (taskNode == 3) {
            status = 7;
        } else if (taskNode == 4) {
            status = 9;
        } else if (taskNode == 1) {
            status = 1;
        }
        operationalRequirementsTable.put("status",status);
        operationalManagementMapper.updateOperationalRequirementsTable(operationalRequirementsTable);
        if (taskNode != 5) {
            //启动流程
            Map<String, Object> requestParam = Maps.newHashMap();
            requestParam.put("processDefinitionKey", "yyxq_event");
            requestParam.put("processType", 1);
            //运营单号
            requestParam.put("processInstanceName", operationalRequirementsTable.get("orderCode"));
            requestParam.put("businessKey", operationalRequirementsTable.get("id"));
            Map<String, Object> variables = Maps.newHashMap();
            variables.put("auditFlag", taskNode);
            variables.put("orderCode",operationalRequirementsTable.get("orderCode"));
            requestParam.put("variables", variables);
            this.startOperationalWorkFlowProcess(requestParam);
        }

        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertOperationalRequirementsTable(OperationalRequirementsTable operationalRequirementsTable)throws Exception {
        //同一用工日期+班组组合，只能提交1次。原订单删除后，才可以新建。
        List<OperationalRequirementsTable> operationalRequirementsTables = operationalManagementMapper.selectOperationalRequirements(operationalRequirementsTable);
        if (operationalRequirementsTables.size() > 0) {
            return -1;
        }
         operationalManagementMapper.insertOperationalRequirementsTable(operationalRequirementsTable);
        Map<String, Object> requestParam = Maps.newHashMap();
        requestParam.put("processDefinitionKey", "yyxq_event");
        requestParam.put("processType", 1);
        requestParam.put("processInstanceName", operationalRequirementsTable.getOperationalOrderCode());
        requestParam.put("businessKey", operationalRequirementsTable.getId());
        Map<String, Object> variables = Maps.newHashMap();
        variables.put("auditFlag", 1);
        requestParam.put("variables", variables);
        variables.put("orderCode",operationalRequirementsTable.getOperationalOrderCode());
        this.startOperationalWorkFlowProcess(requestParam);
        //更新状态
        return 1;
    }
}
